//
//  HomeTableViewController.m
//  CC
//
//  Created by Calvin on 4/19/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//

#import "HomeTableViewController.h"
#import "HomeDetailViewController.h"
#import "UIBarButtonItem+Extension.m"
#import "UIImage+Extension.h"
#import "TitleButton.h"
#import "PopMenu.h"
#import "UIView+Toast.h"
#import "AuthViewController.h"
#import "AFNetworking.h"
#import "AccountModel.h"
#import "AccountTool.h"
#import "UIKit+AFNetworking.h"
#import "UIImage+Extension.h"
#import "StatusModel.h"
#import "MJExtension.h"
#import "LoadStatusesFooter.h"
#import "StatusFrame.h"
#import "StatusCell.h"
#import "HttpTool.h"
#import "HomeStatusesParam.h"
#import "HomeStatusesResult.h"
#import "StatusTool.h"
#import "UserInfoParam.h"
#import "UserInfoResult.h"
#import "UserTool.h"

@interface HomeTableViewController()
@property (nonatomic,strong) NSMutableArray *statuses;
@property (nonatomic,strong) NSMutableArray *statusesFrame;
@property (nonatomic,strong) TitleButton *titleButton;
@property (nonatomic, weak) UIRefreshControl *refresh;
@end

@implementation HomeTableViewController
-(NSMutableArray *)statuses
{
    if (_statuses==nil) {
        _statuses =[NSMutableArray array];
    }
    
    return _statuses;
}

-(NSMutableArray *)statusesFrame
{
    if (_statusesFrame==nil) {
        _statusesFrame=[NSMutableArray array];
    }
    
    return _statusesFrame;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.tableView.backgroundColor = CCColor(211, 211, 211);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setupNavBar];
    [self setupRefresh];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setupUserInfo];
    });
}

-(void)setupNavBar
{
    self.navigationItem.leftBarButtonItem =[UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearch)];
    
    self.navigationItem.rightBarButtonItem =[UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    
    TitleButton *titleButton =[[TitleButton alloc] init];
    AccountModel *account = [AccountTool accountModel];
    NSString *name = account.name;
    
    NSLog(@"NIckName is %@",name);
    CGRect frame = titleButton.frame;
    frame.size.height=35;
    titleButton.frame=frame;
    NSLog(@"before titlebutton frame is %@",NSStringFromCGRect(titleButton.frame));
    if (name) {
        [titleButton setTitle:name forState:UIControlStateNormal];
    }
    else
    {
        [titleButton setTitle:@"首页" forState:UIControlStateNormal];
    }

    [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [titleButton setImage:[UIImage resizedImage:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleButton setBackgroundImage:[UIImage resizedImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted];
    [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView=titleButton;
    self.titleButton=titleButton;
    NSLog(@"after titlebutton frame is %@",NSStringFromCGRect(titleButton.frame));
}

-(void)setupRefresh
{
    UIRefreshControl *refreshControl =[[UIRefreshControl alloc] init];
    [self.tableView addSubview:refreshControl];
    self.refresh=refreshControl;
    [refreshControl addTarget:self action:(@selector(refreshControlStateChange:)) forControlEvents:UIControlEventValueChanged];
    [refreshControl beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self refreshControlStateChange:refreshControl];
    });
}

-(void)refresh:(BOOL)fromSelf
{
    if (self.tabBarItem.badgeValue) {
        [self.refreshControl beginRefreshing];
        [self loadNewStatuses:self.refresh];
    }
    else if (fromSelf)
    {
        NSIndexPath *firstRow = [NSIndexPath indexPathForItem:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:firstRow atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

-(NSArray *)statusFramesWithStatuses:(NSArray *)statuses
{
    NSMutableArray *frames = [NSMutableArray array];
    for (StatusModel *status in statuses) {
        StatusFrame *frame = [[StatusFrame alloc] init];
        frame.status=status;
        [frames addObject:frame];
    }
    return frames;
}

-(void)setupUserInfo
{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool accountModel].access_token;
//    params[@"uid"]=[AccountTool accountModel].uid;
//    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        UserModel *userModel = [UserModel objectWithKeyValues:responseObject];
//        CGRect frame = self.titleButton.frame;
//        frame.size.height=35;
//        self.titleButton.frame=frame;
//        [self.titleButton setTitle:userModel.name forState:UIControlStateNormal];
//        AccountModel *accountModel = [AccountTool accountModel];
//        accountModel.name = userModel.name;
//        [AccountTool save:accountModel];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];

//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool accountModel].access_token;
//    params[@"uid"] = [AccountTool accountModel].uid;
//    [HttpTool get:@"https://api.weibo.com/2/users/show.json" params:params success:^(id responseObj) {
//        UserModel *userModel = [UserModel objectWithKeyValues:responseObj];
//        CGRect frame = self.titleButton.frame;
//        frame.size.height=35;
//        self.titleButton.frame=frame;
//        [self.titleButton setTitle:userModel.name forState:UIControlStateNormal];
//        AccountModel *accountModel = [AccountTool accountModel];
//        accountModel.name = userModel.name;
//        [AccountTool save:accountModel];
//    } failure:^(NSError *error) {
//        
//    }];
    UserInfoParam *params = [[UserInfoParam alloc] init];
    params.access_token = [AccountTool accountModel].access_token;
    params.uid = [AccountTool accountModel].uid;
    
    [UserTool userInfoWithParam:params success:^(UserInfoResult *result) {
        UserModel *user = result;
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
        AccountModel *account = [AccountTool accountModel];
        account.name = user.name;
        [AccountTool save:account];
    } failure:^(NSError *error) {
        NSLog(@"get user info error %@",error);
    }];
}

-(void)refreshControlStateChange:(UIRefreshControl *)refreshControl
{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool accountModel].access_token;
//    StatusModel *firstStatus = [self.statuses firstObject];
//    if (firstStatus) {
//        params[@"since_id"] = firstStatus.idstr;
//        NSLog(@"%@",firstStatus.idstr);
//    }
//    
//    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSMutableArray *newStatuses =[NSMutableArray array];
//        NSArray *statusDictArray = responseObject[@"statuses"];
//        newStatuses = [NSMutableArray arrayWithArray:[StatusModel objectArrayWithKeyValuesArray:statusDictArray]];
//        NSRange range = NSMakeRange(0, newStatuses.count);
//        
//        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:range];
//        [self.statuses insertObjects:newStatuses atIndexes:indexSet];
//        [self.tableView reloadData];
//        [refreshControl endRefreshing];
//        [self showNewStatusCount:newStatuses.count];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
//    }];
    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool accountModel].access_token;
//    StatusModel *firstStatus = [self.statuses firstObject];
//    if (firstStatus) {
//        params[@"since_id"] = firstStatus.idstr;
//        NSLog(@"%@",firstStatus.idstr);
//    }
//    
//    [HttpTool get:@"https://api.weibo.com/2/statuses/home_timeline.json" params:params success:^(id responseObj) {
//        
//        NSMutableArray *newStatuses =[NSMutableArray array];
//        NSArray *statusDictArray = responseObj[@"statuses"];
//        newStatuses = [NSMutableArray arrayWithArray:[StatusModel objectArrayWithKeyValuesArray:statusDictArray]];
//        NSRange range = NSMakeRange(0, newStatuses.count);
//        
//        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:range];
//        [self.statuses insertObjects:newStatuses atIndexes:indexSet];
//        [self.tableView reloadData];
//        [refreshControl endRefreshing];
//        [self showNewStatusCount:newStatuses.count];
//    } failure:^(NSError *error) {
//        NSLog(@"refreshControlStateChange error %@",error);
//    }];
    
    [self loadNewStatuses:refreshControl];
    
}

-(void)loadNewStatuses:(UIRefreshControl *) refreshControl
{
    HomeStatusesParam *param = [[HomeStatusesParam alloc] init];
    param.access_token =[AccountTool accountModel].access_token;
    StatusModel *firstStatus = [self.statuses firstObject];
//    HomeStatusesParam *param = [[HomeStatusesParam alloc] init];
//    StatusFrame *firstStatusFrame = [self.statusesFrame firstObject];
//    StatusModel *firstStatus = firstStatusFrame.status;
    if (firstStatus) {
        param.since_id = @([firstStatus.idstr longLongValue]);
    }
    
    [StatusTool homeStatusesWithParam:param success:^(HomeStatusesResult *result) {
//        NSArray *newStatuses =[StatusModel objectArrayWithKeyValuesArray:result.statuses];
//        NSRange range = NSMakeRange(0, newStatuses.count);
//        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
//        [self.statuses insertObjects:newStatuses atIndexes:indexSet];
//        [self.tableView reloadData];
//        [refreshControl endRefreshing];
//        [self showNewStatusCount:newStatuses.count];
//        NSArray *newFrames=[self statusFramesWithStatuses:[StatusModel objectArrayWithKeyValuesArray:result.statuses]];
         NSArray *newFrames=[self statusFramesWithStatuses:[StatusModel objectArrayWithKeyValuesArray:result.statuses]];
        NSRange range = NSMakeRange(0, newFrames.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statusesFrame insertObjects:newFrames atIndexes:indexSet];
        [self.tableView reloadData];
        [refreshControl endRefreshing];
        [self showNewStatusCount:newFrames.count];
    } failure:^(NSError *error) {
        [refreshControl endRefreshing];
        NSLog(@"Error is %@",error);
    }];
}

-(void)loadMoreStatuses
{
    HomeStatusesParam *param = [[HomeStatusesParam alloc] init];
    param.access_token = [AccountTool accountModel].access_token;
    StatusModel *lastStatus = [self.statuses lastObject];
//    HomeStatusesParam *param = [[HomeStatusesParam alloc] init];
//    StatusFrame *lastStatusFrame = [self.statusesFrame lastObject];
//    StatusModel *lastStatus = lastStatusFrame.status;
    if (lastStatus) {
        param.max_id = @([lastStatus.idstr longLongValue]-1);
    }
    
    [StatusTool homeStatusesWithParam:param success:^(HomeStatusesResult *result) {
//        NSArray *newStatus = [StatusModel objectArrayWithKeyValuesArray:result.statuses];
//        [self.statuses addObjectsFromArray:newStatus];
//        [self.tableView reloadData];

        NSArray *newFrames=[self statusFramesWithStatuses:[StatusModel objectArrayWithKeyValuesArray:result.statuses]];
        [self.statusesFrame addObjectsFromArray:newFrames];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

-(void)showNewStatusCount:(NSInteger)count
{
    UILabel *label = [[UILabel alloc] init];
    if (count) {
        label.text =[NSString stringWithFormat:@"共有%ld条新的微博数据",count];
    }
    else
    {
        label.text=@"没有最新的微博数据";
    }
    
    label.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageWithName:@"timeline_new_status_background"]];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.textColor=[UIColor whiteColor];
    
    label.frame = CGRectMake(0, self.navigationController.navigationBar.frame.size.height-15, self.view.frame.size.width, 35);
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    CGFloat duration=0.75;
    label.alpha=0.0;
    [UIView animateWithDuration:duration animations:^{
        label.transform=CGAffineTransformMakeTranslation(0, label.frame.size.height);
        label.alpha=1.0;
    } completion:^(BOOL finished) {
        CGFloat delay=0.5;
        [UIView animateKeyframesWithDuration:duration delay:delay options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
            label.transform=CGAffineTransformIdentity;
            label.alpha=0.0;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

-(void)showTableViewFooter
{
    CGRect rect = CGRectMake(0, 0, self.tableView.bounds.size.width, 35);
    LoadStatusesFooter *loadStatuesFooter =[[LoadStatusesFooter alloc] initWithFrame:rect];
    self.tableView.tableFooterView=loadStatuesFooter;
}

-(void)titleButtonClick:(UIButton *)titleButton
{
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    UITableView *tableView =[[UITableView alloc] init];
    [tableView setBackgroundColor:[UIColor yellowColor]];
    PopMenu *popMenu = [PopMenu popMenuWithContentView:tableView];
    [popMenu showInRect:CGRectMake(80, 55, 200, 200)];
    popMenu.dimBackground=YES;
    popMenu.arrowPosition=PopMenuArrowPositionCenter;
    popMenu.popMenudelegate=(id)self;
}

-(void)pop{
    AuthViewController *authViewController = [[AuthViewController alloc] init];
    [self.navigationController pushViewController:authViewController animated:YES];
}

-(void)friendsearch
{
    
}

#pragma make - Table view data source
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.statusesFrame.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *identifier =@"cell";
//    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];
//    if (!cell) {
//        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
//    }
//    
//    StatusModel *status =self.statuses[indexPath.row];
//    cell.textLabel.text=status.text;
//    cell.detailTextLabel.text=status.user.name;
//    NSString *imageUrlStr=status.user.profile_image_url;
//    [cell.imageView setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageWithName:@"avatar_default_small"]];
    StatusCell *cell = [StatusCell cellWithTableView:tableView];
    cell.statusFrame=self.statusesFrame[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeDetailViewController *detail =[[HomeDetailViewController alloc] init];
    detail.view.backgroundColor =[UIColor redColor];
    detail.title=@"Detail";
    [self.navigationController pushViewController:detail animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatusFrame *statusFrame = self.statusesFrame[indexPath.row];
    return statusFrame.cellHeight;
}
@end
